<template>
  <view class="detail">
    <view class="fixbg" :style="{ backgroundImage: 'url(' + bg + ')' }"></view>
    <musicHead
      icon="true"
      :title="songDetail.name || ''"
      color="white"
    ></musicHead>
    <view class="container" v-if="!isLoading">
      <scroll-view scroll-y="true">
        <view class="play-music">
          <transition name="imageDis">
            <view
              class="play-music-image"
              @tap="pauseOrPlaying"
              v-if="!showLyric"
            >
              <image
                :src="songDetail.al.picUrl"
                :class="[isplayrotate ? 'isplaying' : '']"
                mode=""
              />
              <text
                class="iconfont"
                :class="playicon"
                v-show="iconIsVisible"
              ></text>
              <view :class="[!isplayrotate ? 'play-music-pause' : '']"></view>
            </view>
          </transition>
          <view
            class="play-music-lyric"
            @tap="showAllLryic"
            ref="scroll"
            :class="[showLyric ? 'play-music-lyric-active' : '']"
          >
            <view
              class="play-music-wrap"
              :style="{
                transform: 'translateY(' + -(lyricIndex - 1) * 82 + 'rpx)',
              }"
            >
              <view
                v-for="(item, index) in songLyric"
                :key="index"
                :class="[index == lyricIndex ? 'active' : '']"
                >{{ item.lyric }}</view
              >
            </view>
          </view>

          <view class="play-music-controller" v-if="!showLyric">
            <text
              class="iconfont icon-shangyishoushangyige"
              @tap="getNextOrPreMusic('pre')"
            ></text>
            <text
              v-if="isplayrotate"
              class="iconfont icon-Pause"
              @tap="pauseOrPlaying"
            ></text>
            <text
              v-else
              class="iconfont icon-yunhang"
              @tap="pauseOrPlaying"
            ></text>
            <text
              class="iconfont icon-xiayigexiayishou"
              @tap="getNextOrPreMusic('next')"
            ></text>
          </view>

          <view class="play-music-like">
            <view class="play-music-like-head">
              <view class="play-music-like-head-left"
                >喜欢这首歌的人也喜欢听</view
              >
              <view
                class="play-music-like-head-right"
                @tap="similaritySong(randomSimilarId)"
              >
                <text class="iconfont icon-yunhang"></text>
                <view>一键收听</view>
              </view>
            </view>
            <view class="play-music-like-body">
              <view
                class="play-music-like-item"
                v-for="(item, index) in songSimi"
                :key="index"
                @tap="similaritySong(item.id)"
              >
                <view class="play-music-like-item-img">
                  <image
                    :src="item.album.picUrl"
                    :lazy-load-margin="0"
                    lazy-load
                    mode=""
                  />
                </view>
                <view class="play-music-like-item-detail">
                  <view>{{ item.name }}</view>
                  <view>
                    <image
                      v-if="
                        item.privilege.flag > 60 && item.privilege.flag < 70
                      "
                      src="../../static/dujia.png"
                      mode=""
                    ></image>
                    <image
                      v-if="item.privilege.maxbr == 999000"
                      src="../../static/sq.png"
                      mode=""
                    ></image>
                    {{ item.artists[0].name }} - {{ item.name }}
                  </view>
                </view>
                <text class="iconfont icon-bofang"></text>
              </view>
              <!-- <view class="play-music-like-item">
                <view class="play-music-like-item-img">
                  <image src="../../static/logo.jpg" mode="" />
                </view>
                <view class="play-music-like-item-detail">
                  <view>蓝</view>
                  <view>
                    <image src="../../static/dujia.png" mode="" />
                    <view>石启柏-蓝</view>
                  </view>
                </view>
                <text class="iconfont icon-bofang"></text>
              </view> -->
            </view>
          </view>

          <!-- 精彩评论 -->
          <view class="music-comment">
            <view class="music-comment-title">精彩评论</view>
            <view
              class="music-comment-item"
              v-for="(item, index) in songComment"
              :key="index"
            >
              <view class="music-comment-img"
                ><image
                  :src="item.user.avatarUrl"
                  mode=""
                  lazy-load
                  :lazy-load-margin="0"
                ></image
              ></view>
              <view class="music-comment-content">
                <view class="music-comment-head">
                  <view class="music-comment-name">
                    <view>{{ item.user.nickname }}</view>
                    <view>{{ item.time | formatTime }}</view>
                  </view>
                  <view class="music-comment-like">
                    {{ item.likedCount | formatCount }}
                    <text class="iconfont icon-like"></text>
                  </view>
                </view>
                <view class="music-comment-text">
                  {{ item.content }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>
<script>
import {
  songDetail,
  songUrl,
  songLyric,
  songSimi,
  songComment,
} from "@/api/index.js";
export default {
  data() {
    return {
      songDetail: {
        al: { picUrl: "../../static/bg.png" },
      },
      songSimi: [],
      songComment: [],
      songLyric: [],
      lyricIndex: 0,
      playicon: "icon-Pause",
      isplayrotate: true,
      iconIsVisible: true,
      tiemr: null,
      lyricTimer: null,
      isLoading: true,
      //是否展示大量歌词
      showLyric: false,
      bg: "https://p2.music.126.net/wSMfGvFzOAYRU_yVIfquAA==/2946691248081599.jpg",
    };
  },
  onLoad(params) {
    // #ifdef H5
    if (this.bgAudioManager) {
      this.bgAudioManager.destroy();
    }
    // #endif
    const { id } = params;
    this.getAllDetailMsg(id);
  },
  onHide() {
    this.destoryTimer();
    this.destoryLyicTimer();
    // #ifdef H5
    if (this.bgAudioManager) {
      this.bgAudioManager.destroy();
      this.isplayrotate = false;
    }
    // #endif
  },
  onUnload() {
    this.destoryTimer();
    this.destoryLyicTimer();
    // #ifdef H5
    if (this.bgAudioManager) {
      this.bgAudioManager.destroy();
      this.isplayrotate = false;
    }
    // #endif
  },
  onShow() {
    this.isplayrotate = true;
  },

  methods: {
    async getAllDetailMsg(songId) {
      uni.showLoading({
        title: "Loading",
      });
      if (songId) {
        this.$store.commit("Detail/NEXT_ID", songId);
        this.$store.commit("Detail/CUR_ID", songId);
        this.$store.commit("Detail/PRE_ID", songId);
      }
      // #ifdef H5
      if (this.bgAudioManager) {
        this.bgAudioManager.destroy();
        this.isplayrotate = false;
      }
      // #endif
      // 要么一起成功要么失败
      try {
        let dataAll = await Promise.all([
          songDetail(songId),
          songSimi(songId),
          songComment(songId),
          songLyric(songId),
          songUrl(songId),
        ]);
        this.songDetail = dataAll[0].songs[0];
        console.log("这是详情", this.songDetail);
        this.songSimi = dataAll[1].songs || [];
        this.songComment = dataAll[2].hotComments || [];

        // 解析歌词
        let lyric = dataAll[3].lrc.lyric;
        let result = [];
        // let reg = /\[(\d+:\d+.\d+)\](.)+\s/g;
        let reg = /\[([^\]]+)\]([^[]+)/g;
        lyric.replace(reg, ($0, $1, $2) => {
          result.push({ time: this.forNumberToSec($1), lyric: $2 });
        });

        // let resultData = [];
        // result.forEach((item) => {
        //   if (item.lyric.length > 18) {
        //     let arr = item.lyric.split(" ");
        //     arr.forEach((element) => {
        //       resultData.push({ time: item.time, lyric: element });
        //     });
        //   } else {
        //     resultData.push({ tiem: item.time, lyric: item.lyric });
        //   }
        // });

        this.songLyric = result;
        //获取音频url
        let url = dataAll[4].data[0].url;
        if (!url) {
          uni.showToast({
            title: "暂无音频资源",
            icon: "error",
            duration: 3000,
          });
          return;
        }
        console.log(url);
        //创建一个播放器实例
        // #ifdef MP-WEIXIN
        this.bgAudioManager = uni.getBackgroundAudioManager();
        this.bgAudioManager.title = this.songDetail.name || "";
        //  #endif

        // #ifdef H5
        if (!this.bgAudioManager) {
          this.bgAudioManager = uni.createInnerAudioContext();
          this.bgAudioManager.play();
          this.destoryTimer();
          this.tiemr = setTimeout(() => {
            this.iconIsVisible = false;
          }, 3000);
          // this.playicon = "icon-bofang";
          // this.isplayrotate = false;
          this.bgAudioManager.autoplay = true;
        }
        //  #endif

        this.bgAudioManager.coverImgUrl = this.songDetail.al.picUrl;
        this.bgAudioManager.src = url;
        this.listenLyicTimer();
        //播放和暂停的回调
        this.bgAudioManager.onPlay(() => {
          (this.playicon = "icon-Pause"), (this.isplayrotate = true);
          this.listenLyicTimer();
        });
        this.bgAudioManager.onPause(() => {
          (this.playicon = "icon-yunhang"), (this.isplayrotate = false);
          this.destoryLyicTimer();
        });

        this.bgAudioManager.onEnded(() => {
          if (!this.$store.state.Detail.nextId) {
            return;
          }
          this.getAllDetailMsg(this.$store.state.Detail.nextId);
          let data = {
            lyricIndex: 0,
          };
          Object.assign(this.$data, data);
        });
        this.isLoading = false;
      } catch (error) {
        this.playicon = "icon-bofang";
        this.isplayrotate = false;
      } finally {
        uni.hideLoading();
      }
    },
    forNumberToSec(val) {
      let arr = val.split(":");
      return (Number(arr[0] * 60) + Number(arr[1])).toFixed(2);
    },
    // 控制播放
    pauseOrPlaying() {
      if (this.bgAudioManager.paused) {
        this.bgAudioManager.play();
      } else {
        this.bgAudioManager.pause();
      }
      this.iconIsVisible = true;
      this.destoryTimer();
      this.tiemr = setTimeout(() => {
        this.iconIsVisible = false;
      }, 3000);
    },

    // 上一首或者下一首
    getNextOrPreMusic(remark) {
      // #ifdef H5
      if (this.bgAudioManager) {
        this.bgAudioManager.destroy();
      }
      // #endif
      if (remark == "next") {
        this.getAllDetailMsg(this.$store.state.Detail.nextId);
      } else {
        this.getAllDetailMsg(this.$store.state.Detail.preId);
      }
      let data = {
        lyricIndex: 0,
      };
      Object.assign(this.$data, data);
    },
    listenLyicTimer() {
      //开启定时器
      this.destoryLyicTimer();
      this.lyricTimer = setInterval(() => {
        for (let i = 0; i < this.songLyric.length; i++) {
          if (
            this.bgAudioManager.currentTime >
            this.songLyric[this.songLyric.length - 1].time
          ) {
            this.lyricIndex = this.songLyric.length - 1;
            break;
          }
          if (
            this.bgAudioManager.currentTime > this.songLyric[i].time &&
            this.bgAudioManager.currentTime < this.songLyric[i + 1].time
          ) {
            this.lyricIndex = i;
          }
          console.log(this.lyricIndex);
        }
      }, 500);
    },
    destoryLyicTimer() {
      clearInterval(this.lyricTimer);
      this.lyricTimer = null;
    },
    destoryTimer() {
      if (this.timer) {
        clearTimeout(this.tiemr);
        this.tiemr = null;
      }
    },

    //播放相似歌曲
    similaritySong(id) {
      this.getAllDetailMsg(id);
      this.$store.commit("Detail/GET_SONGLIST", this.songSimi);
    },

    //展示所有歌词
    showAllLryic() {
      this.showLyric = !this.showLyric;
    },
  },

  computed: {
    randomSimilarId() {
      let idArr = [];
      this.songSimi.forEach((item) => {
        idArr.push(item.id);
      });
      console.log("长度为" + idArr.length);
      // 获得随机数,不含最大值，含最小值
      return idArr[Math.floor(Math.random() * idArr.length)];
    },

    //因为v-for和v-if渲染时机问题所以使用计算属性解决
    resultSongLyric() {
      return this.songLyric.filter((item) => {
        if (item.lyric != "\n") {
          return item;
        } else {
          item.lyric = "";
          return item;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.bg {
  background-image: url("../../static/bg.png");
}

.play-music {
  margin-top: 150rpx;
  // 控制播放状态

  .play-music-image {
    position: relative;
    width: 580rpx;
    height: 580rpx;
    margin: 0 auto 0 auto;
    margin-bottom: 100rpx;
    background-image: url("../../static/disc.png");
    background-size: cover;

    @keyframes move {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }
    & > .isplaying {
      animation-play-state: running;
    }

    & > image {
      animation: 10s linear infinite move;
      animation-play-state: paused;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      width: 370rpx;
      height: 370rpx;
      margin: auto;
      border-radius: 50%;
    }

    & > text {
      position: absolute;
      font-size: 100rpx;
      width: 100rpx;
      height: 100rpx;
      color: white;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
    }
    view {
      width: 230rpx;
      height: 360rpx;
      background-image: url(~@/static/needle.png);
      position: absolute;
      left: 100rpx;
      top: -200rpx;
      right: 0;
      margin: auto;
      background-size: cover;
    }
    .play-music-pause {
      left: 300rpx;
    }
  }

  .play-music-lyric {
    font-size: 38rpx;
    height: 246rpx;
    text-align: center;
    line-height: 82rpx;
    margin: 0 auto 0 auto;
    overflow: hidden;
    transition: 1s all linear;
    .play-music-wrap {
      transition: 0.5s;
      view {
        color: #949495;
        height: 82rpx;
        // overflow: scroll;
        // line-height: 82rpx;
      }
      .active {
        color: white;
        font-size: 48rpx;
      }
    }
  }
  .play-music-lyric:active {
    // transform: translateY(-580rpx);
    height: 726rpx;
    // margin-top: 0rpx;
  }
  .play-music-lyric-active {
    height: 726rpx;
    // margin-top: 0rpx;
  }

  .play-music-controller {
    margin: 100rpx 0rpx 40rpx;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    text {
      font-size: 100rpx;
      color: white;
      opacity: 0.7;
      margin: 0rpx 60rpx;
    }
  }

  .play-music-like {
    margin: 100rpx 32rpx;
    .play-music-like-head {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;

      & > view:nth-child(1) {
        color: white;
        font-size: 36rpx;
      }

      & > view:nth-child(2) {
        display: flex;
        align-items: center;
        display: flex;
        border-radius: 40rpx;
        padding: 10rpx 15rpx;
        border: 2rpx solid white;
        color: white;
        text {
          margin: 0rpx 10rpx;
          font-size: 32rpx;
          // color: white;
        }
        view {
          font-size: 28rpx;
        }
      }
    }
    .play-music-like-body {
      display: flex;
      flex-direction: column;
      .play-music-like-item {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 30rpx;
        color: #a2a2a2;
        .play-music-like-item-img {
          margin-right: 20rpx;
          width: 120prx;
          height: 120rpx;
          border-radius: 30rpx;
          overflow: hidden;
          & > image {
            width: 120rpx;
            height: 120rpx;
          }
        }
        .play-music-like-item-detail {
          // margin-left: 20rpx;
          display: flex;
          flex-direction: column;
          justify-content: center;
          view:nth-child(1) {
            margin-bottom: 20rpx;
            color: white;
            font-size: 30rpx;
            display: -webkit-box; /*弹性伸缩盒子模型显示*/
            -webkit-box-orient: vertical; /*排列方式*/
            -webkit-line-clamp: 1; /*显示文本行数(这里控制多少行隐藏)*/
            overflow: hidden; /*溢出隐藏*/
            text-overflow: ellipsip; /*溢出显示省略号*/
          }
          view:nth-child(2) {
            display: flex;
            flex-direction: row;
            align-items: center;
            display: -webkit-box; /*弹性伸缩盒子模型显示*/
            -webkit-box-orient: vertical; /*排列方式*/
            -webkit-line-clamp: 1; /*显示文本行数(这里控制多少行隐藏)*/
            overflow: hidden; /*溢出隐藏*/
            text-overflow: ellipsip; /*溢出显示省略号*/
            font-size: 28rpx;
            image {
              width: 48rpx;
              height: 24rpx;
              margin-right: 10rpx;
            }
          }
        }
        text {
          font-size: 48rpx;
          color: white;
          margin-left: auto;
        }
      }
    }
  }

  .music-comment {
    margin: 0 32rpx;
  }

  .music-comment-title {
    font-size: 36rpx;
    color: white;
    margin: 50rpx 0;
  }
  .music-comment-item {
    display: flex;
    margin-bottom: 28rpx;
  }
  .music-comment-img {
    width: 66rpx;
    height: 66rpx;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 18rpx;
  }
  .music-comment-img image {
    width: 100%;
    height: 100%;
  }
  .music-comment-content {
    flex: 1;
    color: #cac9cd;
  }
  .music-comment-head {
    display: flex;
    justify-content: space-between;
  }
  .music-comment-name view:nth-child(1) {
    font-size: 24rpx;
  }
  .music-comment-name view:nth-child(2) {
    font-size: 20rpx;
  }
  .music-comment-like {
    font-size: 30rpx;
  }
  .music-comment-text {
    line-height: 40rpx;
    color: white;
    font-size: 28rpx;
    margin-top: 16rpx;
    border-bottom: 1px #595860 solid;
    padding-bottom: 40rpx;
  }
}

.imageDis-enter,
.imageDis-leave-to {
  opacity: 0;
}
/* 整个元素的进入和离开的过程，谁做动画给谁加 */
.imageDis-enter-active,
.imageDis-leave-active {
  transition: 0.5s all linear;
}
/* 进入的终点、离开的起点 */
.imageDis-enter-to,
.imageDis-leave {
  opacity: 1;
}
//过渡的动画
</style>